package com.j1ay.forum.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * @Author J1ay
 * @Date 2021/12/17 19:03
 * @Description
 */

@Component
public class QiniuUtils {

    public static  final String url = "http://spiderman.fun/";
//    public static  final String url = "http://r49i4pza9.hn-bkt.clouddn.com";

    @Value("${qiniu.accessKey}")
    private  String accessKey;
    @Value("${qiniu.accessSecretKey}")
    private  String accessSecretKey;

    private String bucket = "moer-tie2";

    public  boolean upload(MultipartFile file, String fileName){

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);


        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    /**
     * 文件下载
     *
     */
    public String download(String fileName) {
        try {
            String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
            String baseUrl = String.format("%s/%s", url, encodedFileName);
            System.out.println(encodedFileName);
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String downUrl = auth.privateDownloadUrl(baseUrl);
            System.out.println(downUrl);
            return downUrl;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
